<!-- Inspect.vue -->
<template>
  <view>
	  <wd-collapse v-model="value" class="list">
	    <wd-collapse-item
	      v-for="_ in transformedData"
	      :key="_.value"
	      :title="_.label"
	      :name="`inspect${_.value}`"
	    >
        <template #title="{ expanded, disabled, isFirst }">
          <view class="header">
            <text >{{ _.label }}</text>
            <text v-if="_.confirmTime" style="font-weight: normal;font-size: 24rpx;">
              验收时间：{{ dayjs(_.confirmTime).format('YYYY-MM-DD hh:mm:ss') }}
            </text>
            
          </view>
        </template>
        <upload v-model="_.fileUrl" accept="image/*" multiple theme="image" :disabled="_.status==='1'||_.status==='2'" ></upload>
        <wd-button style="margin-top: 4px;margin-right: 2px;" size="small" @click="handleSave(_)" v-if="_.status==='0'&&hasPermission('system:inspect:create')">保存</wd-button>
        <wd-button style="margin-top: 4px;margin-right: 2px;" size="small" @click="handleSubmit(_)" v-if="_.id&&_.status==='0'&&hasPermission('system:inspect:submit-inspect')">提交</wd-button>
        <wd-button style="margin-top: 4px;margin-right: 2px;" size="small" @click="handleReject(_)" v-if="_.status==='1'&&hasPermission('system:inspect:reject-inspect')" >退回验收</wd-button>
        <wd-button style="margin-top: 4px;" size="small" @click="handleConfirm(_)" v-if="_.status==='1'&&hasPermission('system:inspect:confirm-inspect')" >确认验收</wd-button>
	    </wd-collapse-item>
	  </wd-collapse>

	
  </view>
</template>
<script setup>
import dayjs from 'dayjs';	
import { ref, computed, watch, onMounted, reactive } from 'vue';
import { onReady } from '@dcloudio/uni-app';
import {
  useDictionaryStore,
  useUserStore,
  usePermissionStore 
} from '@/store/index.js'
import { getInspectList,updateInspect,createInspect, engineeringConfirmInspect, engineeringRejectInspect ,engineeringSubmitInspect } from '@/api/engineering/detail.js'
import Upload from '@/packageA/components/upload/upload.vue';
const props = defineProps({
  // 订单id
  engineeringId: {
    type: Number,
    required: true
  },
});

// 字典仓库
 const dictionaryStore = useDictionaryStore()
 // 用户仓库
 const userStore = useUserStore()
// 权限参数
const permissionStore = usePermissionStore()
const hasPermission = (permissions) => {
	console.log(permissionStore.permissions,'permissions');
	console.log(permissionStore.hasPermission(permissions),'ll');
      return permissionStore.hasPermission(permissions)
    }


 const transformedData = ref([])
// 获取验收单
const hanldeGetInspetList = () => {
  getInspectList({pageSize:-1,engineeringId:props.engineeringId}).then(data => {
    transformedData.value = transformData(data.list, dictionaryStore.get('acceptance_form_type'));
    console.log(transformedData.value,'trans');
    
  })
}

const transformData=(dataList, formTypes) => {
  // 创建默认的返回结果
  const defaultResult = formTypes.map(item => ({
    ...item,
    fileUrl: [],
    status: "0" 
  }));

  if (!Array.isArray(dataList) || dataList.length === 0) {
    return defaultResult;
  }

  // 根据 stage 和 value 匹配，填充 fileUrl
  const result = defaultResult.map(formType => {
    const matchedItem = dataList.find(item => item.stage === formType.value);
    if (matchedItem) {
      return {
        ...formType,
        id: matchedItem.id,
        engineeringId: matchedItem.engineeringId,
        stage: matchedItem.stage,
        status: matchedItem.status,
        fileUrl: JSON.parse(matchedItem.fileUrl),
        confirmTime: matchedItem.confirmTime,
        createTime: matchedItem.createTime
      };
    } else {
      return { ...formType, fileUrl: [],status: "0" };
    }
  });

  return result;
}
const value = ref(['inspect1'])

watch(() => transformedData.value, (newVal) => {
  console.log("transformedData 更新:", newVal);
}, { deep: true });
onMounted(() => {
  hanldeGetInspetList();
});
// 保存
const handleSave = (row) => {
  console.log(row,'row');
  if(row.id) {
    const params = {id:row.id,fileUrl:row.fileUrl}
    updateInspect(params).then(res => {
      hanldeGetInspetList()
      uni.showToast({
    		title: '保存成功',
    		icon: 'success'
    	})
    }).catch((error) => {
    	uni.showToast({
    		title: error,
    		icon: 'error'
    	})
    })
  } else {
    if(row.fileUrl.length === 0) {
      MessagePlugin.error('请上传图片');
      return
    }
    const params = {stage:row.value,fileUrl:row.fileUrl,engineeringId:props.engineeringId}
    createInspect(params).then(res => {
      hanldeGetInspetList()
        uni.showToast({
    		title: '保存成功',
    		icon: 'success'
    	})
    }).catch((error) => {
    	uni.showToast({
    		title: error,
    		icon: 'error'
    	})
    })
  }
  
}

// 提交
const handleSubmit = (row) => {
  const params = {id:row.id, engineeringId:row.engineeringId,}
  engineeringSubmitInspect(params).then(res => {
      hanldeGetInspetList()
        uni.showToast({
    		title: '提交成功',
    		icon: 'success'
    	})
    }).catch((error) => {
    	uni.showToast({
    		title: error,
    		icon: 'error'
    	})
    })
  
}

// 退回
const handleReject = (row) => {
  const params = {id:row.id, engineeringId:row.engineeringId}
  engineeringRejectInspect(params).then(res => {
      hanldeGetInspetList()
        uni.showToast({
    		title: '退回成功',
    		icon: 'success'
    	})
    }).catch((error) => {
    	uni.showToast({
    		title: error,
    		icon: 'error'
    	})
    })
  
}
// 确认
const handleConfirm = (row) => {
  const params = {id:row.id,engineeringId:row.engineeringId}
  engineeringConfirmInspect(params).then(res => {
      hanldeGetInspetList()
        uni.showToast({
    		title: '确认成功',
    		icon: 'success'
    	})
    }).catch((error) => {
    	uni.showToast({
    		title: error,
    		icon: 'error'
    	})
    })
  
}

</script>
<style lang="scss" scoped>
  .custom-layout {
	  height: calc(100vh - 300px);
  }
  .header {
    display: flex;
    justify-content: space-between;
  }
</style>